package chat.message;

import javax.swing.text.DateFormatter;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ChatMessage {
    private static final Pattern urlPattern = Pattern.compile("((http|ftp|https)://(\\w|\\p{Punct})*)|(www\\.(\\w|\\p{Punct})*)");

    private String from;
    private String message;
    private Date date;

    public ChatMessage(String from, String message, Date date) {
        this.from = from;
        this.message = message;
        this.date = date;
    }

    public String toJSON() {
        StringBuffer retVal = new StringBuffer();

        retVal.append("{");
        if (from == null || from.isEmpty() || !from.matches("\\S*")) {
            retVal.append("from:").append("'").append("Anonymous").append("',");
        } else {
            retVal.append("from:").append("'").append(normalizeForJS(from)).append("',");
        }
        if (message != null) {
            retVal.append("message:").append("'").append(normalizeForJS(message)).append("',");
        }
        if (date != null) {
            DateFormat dateFormat = new SimpleDateFormat("dd.MM.yyyy");
            retVal.append("date:").append("'").append(dateFormat.format(date)).append("',");

            DateFormat timeFormat = new SimpleDateFormat("HH:mm:ss");
            retVal.append("time:").append("'").append(timeFormat.format(date)).append("',");
        }
        retVal.append("}");

        return retVal.toString();
    }

    private String normalizeForJS(String input) {
        String output = input;

        output = normalizeLinks(output);
        output = output.replaceAll("'", "\\\\'");
        output = output.replaceAll("\r\n", "<br/>");
        output = output.replaceAll("\"", "&#34;");
        
        return output;
    }

    private String normalizeLinks(String input) {
        String output = input;

        Matcher matcher = urlPattern.matcher(input);
        while (matcher.find()) {
            String link = matcher.group();
            output = output.replaceAll(link, "<a href=" + (link.matches("(http.*|ftp.*|https.*)") ? link : "http://" + link) + " target=_blank>" + link + "</a>");
        }

        return output;
    }
}
